package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.common.utils.appkit.ConfigKit;
import com.firefightingiot.firefightingiot.common.utils.appkit.FirefightingiotKit;
import com.firefightingiot.firefightingiot.config.rocketmq.UserProducer;
import com.firefightingiot.firefightingiot.model.*;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.MyLogger;
import com.firefightingiot.firefightingiot.support.utils.WebUtil;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.*;
import com.firefightingiot.firefightingiot.web.mapper.alarmtoday.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//import org.bytedeco.javacpp.opencv_core;
//import org.bytedeco.javacv.*;

@Service
@Slf4j
public class AlarmService extends BaseService {

    @Resource
    public MyLogger logger;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    @Resource
    private DeviceAlarmLogMapper deviceAlarmLogMapper;
    @Resource
    private DeviceAlarmLogImgMapper deviceAlarmLogImgMapper;
    @Resource
    FireService fireService;
    @Resource
    UseDictMapper useDictMapper;
    @Resource
    private DeviceAlarmLogAllTodayMapper deviceAlarmLogAllTodayMapper;
    @Resource
    private DeviceAlarmLogElectricFireTodayMapper deviceAlarmLogElectricFireTodayMapper;
    @Resource
    private DeviceAlarmLogFireWaterTodayMapper deviceAlarmLogFireWaterTodayMapper;
    @Resource
    private DeviceAlarmLogSmokeTodayMapper deviceAlarmLogSmokeTodayMapper;
    @Resource
    private DeviceAlarmLogGasTodayMapper deviceAlarmLogGasTodayMapper;
    @Resource
    private DeviceAlarmLogVisualizationTodayMapper deviceAlarmLogVisualizationTodayMapper;
    @Resource
    private FireAddAlarmService alarmAddFireService;
    @Resource
    private AsyncService asyncService;
    @Resource
    private UserProducer userProducer;
    @Resource
    private DeviceAlarmEventMapper deviceAlarmEventMapper;

    /**
     * 报警日志添加
     *
     * @param
     * @return
     */
    public RespEntity add(JSONObject jsonParam) throws ParseException, InterruptedException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("----------iotalramadd" + jsonParam.toString() + "--------------------");
        List<DeviceBusiness> deviceBusinessList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusinessList.isEmpty()) return RespEntity.fail("设备编号错误");
        DeviceBusiness deviceBusiness = deviceBusinessList.get(0);
        if (deviceBusiness.getDeviceClassify().equals("2")) {
            logger.info("******************php****************" + jsonParam.toString() + "*************************************");
        }
        //更新最新时间的和设备的状态为报警
        DeviceBusiness deviceBusinessN = new DeviceBusiness();
        deviceBusinessN.setId(deviceBusiness.getId());
        deviceBusinessN.setNormalUpdateTime(DateUtil.now());
        deviceBusinessN.setCurrentstate("2");
        deviceBusinessMapper.updateById(deviceBusinessN);
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("homeId", deviceBusiness.getOrgId());
        jsonParamN.put("id", deviceBusiness.getBusinessId());
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        //rest请求获取所有的机构id
        //com.alibaba.fastjson.JSONObject orgIds = makeDataForToken(jsonParamN, "systemsetup", "config", "orgAllListJava", "systemsetup");
        //赋值数据和保存数据:DeviceAlarmLog
        DeviceAlarmLog deviceAlarmLog = new DeviceAlarmLog();
        String id = "";
        if (deviceBusiness.getDeviceClassify().equals("6")) {
            id = jsonParam.getStr("uuid");
        } else {
            id = UUID.randomUUID().toString();
        }
        deviceAlarmLog.setId(id);
        deviceAlarmLog.setAllId(deviceBusiness.getAllId());
        jsonParam.put("orgIds", deviceBusiness.getAllId());
        deviceAlarmLog.setDeviceId(deviceBusiness.getId());
        deviceAlarmLog.setNumber(deviceBusiness.getNumber());
        deviceAlarmLog.setDeviceClassify(deviceBusiness.getDeviceClassify());
        deviceAlarmLog.setDeviceType(deviceBusiness.getDeviceType());
        deviceAlarmLog.setAlarmType(jsonParam.getStr("alarmType"));
        deviceAlarmLog.setAlarmTypeName(jsonParam.getStr("alarmTypeName"));
        deviceAlarmLog.setContent(jsonParam.getStr("content"));
        deviceAlarmLog.setAlarmtime(jsonParam.getDate("alarmtime"));
        deviceAlarmLog.setPosition(deviceBusiness.getPosition());
        deviceAlarmLog.setOrgId(deviceBusiness.getOrgId());
        deviceAlarmLog.setBusinessId(deviceBusiness.getBusinessId());
        deviceAlarmLog.setBusinessName(deviceBusiness.getBusinessName());
        deviceAlarmLog.setFireRating(businessDetail.getString("fireRating"));
        deviceAlarmLog.setHandle(false);
        deviceAlarmLog.setAlarmPhone(deviceBusiness.getAlarmPhone());
        deviceAlarmLog.setSupervise("督办");
        deviceAlarmLog.setHandletime(null);
        deviceAlarmLog.setHandlePerson(null);
        deviceAlarmLog.setInfoconfirm(null);
        deviceAlarmLog.setHandleRemark(null);
        deviceAlarmLog.setUnreadstate(false);
        deviceAlarmLog.setArea(businessDetail.getString("area"));
        deviceAlarmLog.setAreaName(businessDetail.getString("areaName"));
        String areaName[] = businessDetail.getString("areaName").split(",");
        if (areaName.length >= 3) {
            deviceAlarmLog.setCity(areaName[1]);
            deviceAlarmLog.setRegion(areaName[2]);
        } else if (areaName.length >= 4) {
            deviceAlarmLog.setCity(areaName[1]);
            deviceAlarmLog.setRegion(areaName[2]);
            deviceAlarmLog.setStreet(areaName[3]);
        }
        deviceAlarmLog.setIsws(jsonParam.getInt("isws"));
        deviceAlarmLog.setFireId(UUID.randomUUID().toString().replace("-", ""));
        deviceAlarmLogMapper.insert(deviceAlarmLog);
        if (deviceBusiness.getDeviceClassify().equals("1")) {
            deviceAlarmLog.put("table", "device_alarm_log_electric_fire_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("2")) {
            deviceAlarmLog.put("table", "device_alarm_log_fire_water_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("3")) {
            deviceAlarmLog.put("table", "device_alarm_log_smoke_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("4")) {
            deviceAlarmLog.put("table", "device_alarm_log_gas_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("5")) {
            deviceAlarmLog.put("table", "device_alarm_log_auto_network_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("6")) {
            deviceAlarmLog.put("table", "device_alarm_log_visualization_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        } else if (deviceBusiness.getDeviceClassify().equals("7")) {
            deviceAlarmLog.put("table", "device_alarm_log_fire_extinguisher_today");
            deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        }
        deviceAlarmLog.put("table", "device_alarm_log_all_today");
        deviceAlarmLogAllTodayMapper.insertLogs(deviceAlarmLog);
        if (StrUtil.isNotBlank(jsonParam.getStr("path"))) {
            String[] imgs = jsonParam.getStr("path").split(";;");
            int ii = 0;
            for (String img : imgs) {
                ii = ii + 1;
                DeviceAlarmLogImg deviceAlarmLogImg = new DeviceAlarmLogImg();
                deviceAlarmLogImg.setId(UUID.randomUUID().toString());
                deviceAlarmLogImg.setDeviceAlarmLogId(id);
                deviceAlarmLogImg.setAlarmOrResolve(1);
                deviceAlarmLogImg.setPath(img);
                if (ii == 1) {
                    deviceAlarmLogImg.setName("报警图片地址");
                    deviceAlarmLogImg.setType(1);
                } else {
                    deviceAlarmLogImg.setName("报警视频地址");
                    deviceAlarmLogImg.setType(2);
                }
                deviceAlarmLogImgMapper.insert(deviceAlarmLogImg);
            }
        }
        jsonParam.put("businessId", deviceAlarmLog.getBusinessId());
        jsonParam.put("position", deviceAlarmLog.getPosition());
        jsonParam.put("deviceClassify", deviceAlarmLog.getDeviceClassify());
        String orgIds1 = deviceBusiness.getAllId();
        jsonParam.put("orgIds", orgIds1);
        return RespEntity.success(id);
    }

    /**
     * 处置模块分类功能(总历史记录点处置时触发)
     *
     * @param
     * @return
     */
    public RespEntity typeHandle(JSONObject jsonParam) throws InterruptedException, ParseException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //页面不传handletime，自己赋值一下
        if (StrUtil.isBlank(jsonParam.getStr("handletime"))) {
            jsonParam.put("handletime", DateUtil.now());
        }
        DeviceAlarmLog deviceAlarmLog = deviceAlarmLogMapper.selectById(jsonParam.getStr("id"));
        if (deviceAlarmLog == null) return RespEntity.fail("报警日志id不存在");
        jsonParam.put("number", deviceAlarmLog.getNumber());
        //传消防数据
        JSONObject jsonParamFire = new JSONObject();
        if (jsonParam.getBool("batchHandle")) {
            asyncService.setAlarmEvent(deviceAlarmLog.getNumber(),jsonParam.getStr("handletime"));
            deviceAlarmLogMapper.updateByNumber(jsonParam);//根据number修改日志为已处理
            //更改设备状态为报警
            DeviceBusiness alarmDeviceBusiness = new DeviceBusiness();
            alarmDeviceBusiness.setCurrentstate("1");
            deviceBusinessMapper.update(alarmDeviceBusiness, new QueryWrapper<DeviceBusiness>().eq("number", deviceAlarmLog.getNumber()));
        } else {
            deviceAlarmLogMapper.updateByLogId(jsonParam);
            //同一个number的未处理的报警信息
            int noHandleLogCount = deviceAlarmLogMapper.selectCount(new QueryWrapper<DeviceAlarmLog>().eq("is_handle", 0).eq("number", deviceAlarmLog.getNumber()));
            if (noHandleLogCount == 0) {
                //更改设备状态为正常
                DeviceBusiness alarmDeviceBusiness = new DeviceBusiness();
                alarmDeviceBusiness.setCurrentstate("1");
                alarmDeviceBusiness.setId(deviceAlarmLog.getDeviceId());
                deviceBusinessMapper.updateById(alarmDeviceBusiness);
            }
            DeviceAlarmEvent deviceAlarmEvent = new DeviceAlarmEvent();
            deviceAlarmEvent.setDeviceAlarmLogId(deviceAlarmLog.getId());
            deviceAlarmEvent.setTime(jsonParam.getStr("handletime"));
            deviceAlarmEvent.setEventName("事件解除");
            deviceAlarmEventMapper.insert(deviceAlarmEvent);
        }
        return RespEntity.success();
    }


    /**
     * @Author YangYu
     * @Description 一键处置
     * @Date Created in 10:52 2022/5/7
     * @Param [jsonParam]
     */

    public RespEntity oneClickHandle(JSONObject jsonParam) throws InterruptedException, ParseException {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //页面不传handletime，自己赋值一下
        if (StrUtil.isBlank(jsonParam.getStr("handletime"))) {
            jsonParam.put("handletime", DateUtil.now());
        }
        //asyncService.handle(jsonParam);
        return RespEntity.success();
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy");
        String y = format.format(date);
        format = new SimpleDateFormat("MM");
        String m = format.format(date);
        format = new SimpleDateFormat("dd");
        String d = format.format(date);
        format = new SimpleDateFormat("HH:mm");
        String h = format.format(date);
        return y + "年" + m + "月" + d + "日" + h + "分";
    }

    /**
     * 更多(历史)报警信息列表查询
     *
     * @param
     * @return
     */
    public RespEntity alarmInfoListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        if (userType.equals("1")) {//为机构用户
            //rest请求系统设置模块的机构和子机构列表接口
            JSON jsons = makeDataForJSONForToken(jsonParam, "systemsetup", "config", "orgAllList", "systemsetup");
            if (jsons instanceof com.alibaba.fastjson.JSONObject) {
                com.alibaba.fastjson.JSONObject weekAlarmObjectN = (com.alibaba.fastjson.JSONObject) jsons;
                if (StrUtil.isNotBlank(weekAlarmObjectN.getString("methodCodeFlag"))) {
                    return RespEntity.expire();
                }
                return RespEntity.fail(((com.alibaba.fastjson.JSONObject) jsons).getString("msg"));
            } else {
                com.alibaba.fastjson.JSONArray orgIdList = (com.alibaba.fastjson.JSONArray) jsons;
                if (orgIdList != null && !orgIdList.isEmpty()) {
                    jsonParam.put("orgIdList", orgIdList);
                    jsonParam.put("orgIdListFlag", "1");
                }
            }
        } else if (userType.equals("2")) {//为单位用户
            jsonParam.put("businessId", homeId);
        }
        if (jsonParam.containsKey("isHandle")) {
            if (jsonParam.getBool("isHandle")) jsonParam.put("isHandle", 1);
            if (!jsonParam.getBool("isHandle")) jsonParam.put("isHandle", 0);
        }
        IPage<DeviceAlarmLog> pageList = deviceAlarmLogMapper.deviceAlarmLogListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * 报警信息详情
     *
     * @param jsonParam
     * @return
     */
    public RespEntity detail(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        DeviceAlarmLog deviceAlarmLog = deviceAlarmLogMapper.selectById(jsonParam.getStr("id"));
        deviceAlarmLog.put("alarmtime", DateUtil.format(deviceAlarmLog.getAlarmtime(), "yyyy-MM-dd HH:mm:ss"));
        deviceAlarmLog.put("handletime", DateUtil.format(deviceAlarmLog.getHandletime(), "yyyy-MM-dd HH:mm:ss"));
        UseDict useDict = useDictMapper.selectById(deviceAlarmLog.getAlarmType());
        deviceAlarmLog.put("alarmTypeName", useDict.getName());
        if (deviceAlarmLog.getDeviceClassify().equals("6") || deviceAlarmLog.getDeviceClassify().equals("11") || deviceAlarmLog.getDeviceClassify().equals("12") || deviceAlarmLog.getDeviceClassify().equals("13") || deviceAlarmLog.getDeviceClassify().equals("14") || deviceAlarmLog.getDeviceClassify().equals("16") || deviceAlarmLog.getDeviceClassify().equals("15") || deviceAlarmLog.getDeviceClassify().equals("17")) {
            DeviceAlarmLogImg deviceAlarmLogImg = deviceAlarmLogImgMapper.selectOne(new QueryWrapper<DeviceAlarmLogImg>().eq("device_alarm_log_id", jsonParam.getStr("id")).eq("type", "1"));
            deviceAlarmLog.put("AlarmImg", deviceAlarmLogImg.getPath());
        }
        return RespEntity.success(deviceAlarmLog);
    }

    /**
     * @param params
     * @return
     * @Title: getTemplte <br>
     * @Description: (下载模板) <br>
     * @author 石延杰<br>
     */

    public RespEntity getTemplte(Map<String, Object> params) {
        List<Map<String, String>> fieldList = new ArrayList<>();
        Map<String, String> map = new LinkedHashMap<>();
        int num = 2;
        map.put("序号", "");
        map.put("省份", "");
        map.put("市级", "");
        map.put("区县", "");
        map.put("街道", "");
        map.put("单位名称", "");
        map.put("安装位置", "");
        map.put("设备编码", "");
        map.put("联系人", "");
        map.put("电话1", "");
        map.put("电话2", "");
        map.put("安装人员", "");
        map.put("设备更换记录", "");
        map.put("安装时间", "");
        map.put("支付方式", "");
        map.put("备注", "");
        fieldList.add(map);
        String repath = ConfigKit.getStr("excelSavePath", "excel");
        StringBuffer url = WebUtil.getRequest().getRequestURL();
        String code = UUID.randomUUID().toString();
        String webPath = "";
        String fileName = "import_part(" + "数据导入" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
        webPath = url.toString().replace("/firefightingiot/device/getTemplte", "/downloadExcel?fileName=" + fileName);
        ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.write(fieldList);
        writer.renameSheet("导入");
        // 关闭writer，释放内存
        writer.close();
        return RespEntity.success(webPath);
    }

    @Resource
    RegionMapper regionMapper;

    /**
     * @param params
     * @return
     * @Title: addUpload <br>
     * @Description: (上传) <br>
     * @author 石延杰<br>
     */
    public RespEntity addUpload(Map<String, Object> params) throws Exception {
        String webPath = "";
        Map<String, String> map = new LinkedHashMap<>();//组装excel表应该有的列名
        map.put("序号", "");
        map.put("省份", "");
        map.put("市级", "");
        map.put("区县", "");
        map.put("街道", "");
        map.put("街道编号", "");
        map.put("机构名称", "");
        map.put("机构ID", "");
        map.put("上级机构ID", "");
        map.put("单位名称", "");
        map.put("单位ID", "");
        map.put("设备分类", "");
        map.put("设备分类编号", "");
        map.put("安装位置", "");
        map.put("设备编号", "");
        map.put("联系人", "");
        map.put("电话1", "");
        map.put("电话2", "");
        map.put("安装人员", "");
        map.put("安装时间", "");
        List<Map<String, Object>> excelList = (List<Map<String, Object>>) params.get("listData");//获取excel表中的数据
        List<Map<String, Object>> removeList = new ArrayList<>();//删除的list
        //rest请求行政区划集合
        List<Region> regionList = regionMapper.selectList(new QueryWrapper<Region>());
        Map<String, String> regionNameMap = new HashMap<>();//行政区划的映射：最底层行政区划：三级名称
        Map<String, String> regionPidMap = new HashMap<>();//行政区划的映射：最底层行政区划：所有级的id
        List<String> regionIdList = new ArrayList<>();//行政区划的id集合
        for (Region region : regionList) {
            regionNameMap.put(region.getId(), region.getAllname());
            regionPidMap.put(region.getId(), region.getAllid());
            regionIdList.add(region.getId());
        }
        //获取目前有的设备编号
        List<DeviceBusiness> deviceBusinessOldList = deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>());
        List<String> numberList = new ArrayList<>();
        for (DeviceBusiness d : deviceBusinessOldList) {
            numberList.add(d.getNumber());
        }
        //之后新增的设备
        List<String> numberExcelList = new ArrayList<>();
        //存储新增的单位
        Map<String, String> buMap = new HashMap<>();//单位名称：单位id
        //查询现在的单位id集合，之后新增了累加在上边
        List<String> allBuIdList = new ArrayList<>();
        //存储新增的机构
        Map<String, String> orgMap = new HashMap<>();//机构名称：机构id
        //查询现在的机构id集合，之后新增了累加在上边
        List<String> allOrgIdList = new ArrayList<>();
        //判断excel中的列名和应该有的列名是不是一致
        if (excelList != null && excelList.size() > 0) {
            Map<String, Object> excelMap = excelList.get(0);
            Set<String> set = excelMap.keySet();
            for (String s : set) {
                if (!map.containsKey(s)) {
                    return RespEntity.fail("文件表头不匹配");
                }
            }
        }
        List<LinkedHashMap<String, Object>> errorList = new ArrayList<>();//出错的list
        SqlSession session = getSqlSession();
        boolean errorFlag = true;
        try {
            DeviceBusinessMapper deviceMapper = getMapper(session, DeviceBusinessMapper.class);
            List<?> object = new ArrayList<>();
            BigData data = new BigData(excelList);
            for (int i = 0; i < data.getNum(); i++) {
                //boolean insertFlag = false;
                List<DeviceBusiness> insertDeviceList = new ArrayList<>();//存储一千条要保存的DeviceBusiness集合
                List<Business> insertBusinessList = new ArrayList<>();//存储一千条要保存的Business集合
                List<Organization> insertOrganizationList = new ArrayList<>();//存储一千条要保存的Organization集合
                List<Map<String, Object>> dataMapList = data.getData(i);//excel中一组数据
                for (Map<String, Object> dataMap : dataMapList) {
                    Set<String> set = dataMap.keySet();
                    String error = "";//错误信息
                    String buId = "";//单位id
                    String orgId = "";//机构id
                    String orgPId = "";//机构pid
                    String buName = "";//单位名称
                    String orgName = "";//机构名称
                    String area = "";//街道编号
                    String number = "";//设备编号
                    String deviceClassify = "";//设备分类编号
                    String phone1 = "";//电话1
                    String phone2 = "";//电话2
                    for (String s : set) {
                        if (dataMap.get(s) == null) dataMap.put(s, "");//防止下载错误list的时候，为空时错行
                        System.out.println(s + "------------------" + dataMap.get(s).toString());
                        //为空时为不符合的数据
                        if (s.equals("街道编号") || s.equals("机构名称") || s.equals("单位名称") || s.equals("设备分类编号") || s.equals("设备编号") || s.equals("上级机构ID")) {
                            if (s.equals("街道编号")) area = dataMap.get(s).toString();
                            if (s.equals("设备编号")) number = dataMap.get(s).toString();
                            if (s.equals("单位名称")) buName = dataMap.get(s).toString();
                            if (s.equals("机构名称")) orgName = dataMap.get(s).toString();
                            if (s.equals("上级机构ID")) orgPId = dataMap.get(s).toString();
                            if (s.equals("设备分类编号")) deviceClassify = dataMap.get(s).toString();
                            String value = dataMap.get(s).toString();
                            if (value == null || value == "") {
                                errorFlag = false;
                                error = error + s + "不能为空;";
                            }
                        }
                        if (s.equals("机构ID")) orgId = dataMap.get(s).toString();
                        if (s.equals("单位ID")) buId = dataMap.get(s).toString();
                        if (s.equals("电话1")) phone1 = dataMap.get(s).toString();
                        if (s.equals("电话2")) phone2 = dataMap.get(s).toString();
                    }
                    //errorFlag
                    if (errorFlag) {
//                        if(numberList.contains(number)){
//                            error = error + "数据库已存在此设备编码;";
//                            errorFlag = false;
//                        }else if(numberExcelList.contains(number)){
//                            error = error + "excel中已存在此设备编码;";
//                            errorFlag = false;
//                        }
//                        if(StrUtil.isNotBlank(buId) && !allBuIdList.contains(buId)){
//                            error = error + "单位ID不存在;";
//                            errorFlag = false;
//                        }
//                        if(StrUtil.isNotBlank(orgId) && !allBuIdList.contains(orgId)){
//                            error = error + "机构ID不存在;";
//                            errorFlag = false;
//                        }
//                        if(!regionIdList.contains(area)){
//                            error = error + "街道编号不存在;";
//                            errorFlag = false;
//                        }
//                        if(StrUtil.isNotBlank(phone1) && phone1.length()!=11){
//                            error = error + "电话1不为11位;";
//                            errorFlag = false;
//                        }
//                        if(StrUtil.isNotBlank(phone2) && phone2.length()!=11){
//                            error = error + "电话2不为11位;";
//                            errorFlag = false;
//                        }
                    }
                    //不符合的数据剔除，符合的保留
                    if (!errorFlag) {
                        LinkedHashMap<String, Object> erroMap = new LinkedHashMap<>();
                        erroMap.put("错误信息", error);
                        removeList.add(dataMap);
                        erroMap.putAll(dataMap);
                        errorList.add(erroMap);
                        errorFlag = true;
                    } else {
                        //新增机构
                        if (StrUtil.isBlank(orgId)) {
                            Organization organization = new Organization();
                            organization.setDes(null);
                            orgId = UUID.randomUUID().toString();
                            organization.setId(orgId);
                            organization.setName(orgName);
                            organization.setPid(orgPId);
                            insertOrganizationList.add(organization);
                            orgMap.put(orgName, orgId);
                            allOrgIdList.add(orgId);
                        }
                        //新增企业
                        if (StrUtil.isBlank(buId)) {
                            Business business = new Business();
                            buId = UUID.randomUUID().toString();
                            business.setId(buId);
                            business.setOrgId(orgId);
                            business.setCreatetime(new Date());
                            business.setOneResponPersonName(dataMap.get("联系人").toString());
                            business.setOneResponPersonPhone(dataMap.get("电话1").toString());
                            business.setSafeResponPersonName(dataMap.get("联系人").toString());
                            business.setSafeResponPersonPhone(dataMap.get("电话2").toString());
                            business.setName(buName);
                            business.setAddr(buName);
                            business.setDel(false);
                            business.setArea(regionPidMap.get(area));
                            business.setAreaName(regionNameMap.get(area));
                            insertBusinessList.add(business);
                            buMap.put(buName, buId);
                            allBuIdList.add(buId);
                        }
                        //新增设备
                        DeviceBusiness deviceBusiness = new DeviceBusiness();
                        deviceBusiness.setId(UUID.randomUUID().toString());
                        deviceBusiness.setNumber(number);
                        deviceBusiness.setBusinessId(buId);
                        deviceBusiness.setBusinessName(buName);
                        deviceBusiness.setDeviceClassify(deviceClassify);
                        deviceBusiness.setOrgId(orgId);
                        deviceBusiness.setPosition(dataMap.get("安装位置").toString());
                        if (StrUtil.isNotBlank(dataMap.get("安装时间").toString())) {
                            deviceBusiness.setInstalltime(dataMap.get("安装时间").toString());
                        } else {
                            deviceBusiness.setInstalltime(null);
                        }
                        if (deviceClassify.equals("4")) {
                            deviceBusiness.setDeviceType("12");
                        }
                        deviceBusiness.setInstallperson(dataMap.get("安装人员").toString());
                        deviceBusiness.setCreatetime(new Date());
                        deviceBusiness.setCurrentstate("1");
                        deviceBusiness.setNormalUpdateTime(DateUtil.now());
                        insertDeviceList.add(deviceBusiness);
                        numberExcelList.add(dataMap.get("设备编号").toString());
                        numberExcelList.add(number);
                        errorFlag = true;
                    }
                }
                if (insertDeviceList != null && insertDeviceList.size() > 0) {
                    if (insertOrganizationList != null && insertOrganizationList.size() > 0) {
                        //rest请求系统设置模块批量新增机构
                    }
                    if (insertBusinessList != null && insertBusinessList.size() > 0) {
                        //rest请求一企一档模块批量新增机构
                    }
                    deviceMapper.insertZB(insertDeviceList);
                    //根据设备分类组装各个模块的设备集合，rest请求各个模块去批量添加设备

                    commit(session);
                }
            }
            //存错误list到缓存
            if (errorList != null && errorList.size() > 0) {
                String repath = ConfigKit.getStr("excelSavePath", "excel");
                StringBuffer url = WebUtil.getRequest().getRequestURL();
                String fileName = "import_Error(" + "导入错误信息" + ")_" + DateUtil.format(new Date(), "yyyyMMDD") + RandomUtil.randomNumbers(10) + ".xlsx";
                webPath = url.toString().replace("/firefightingiot/alarmInfo/Upload", "/firefightingiot/alarmInfo/downloadExcel?fileName=" + fileName);
                ExcelWriter writer = ExcelUtil.getWriter(repath + fileName);
                // 一次性写出内容，使用默认样式
                writer.write(errorList);
                writer.setColumnWidth(1, 30);
                writer.setColumnWidth(2, 30);
                writer.setColumnWidth(3, 30);
                writer.renameSheet("导入错误信息");
                // 关闭writer，释放内存
                writer.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            closeSession(session);
        }
        excelList.removeAll(removeList);
        // 拼装返回结果
        JSONObject result = new JSONObject();
        result.put("ErrorNum", errorList.size());
        result.put("SuccesNum", excelList.size());
        result.put("webPath", webPath);
        return RespEntity.success(result);
    }

    /**
     * @param map
     * @return
     * @Title: sortHashMap <br>
     * @Description: (修改map的key顺序) <br>
     * @author 石延杰<br>
     */
    public static LinkedHashMap<String, Object> sortHashMap(Map<String, Object> map) {
        LinkedHashMap<String, Object> sortedMap = new LinkedHashMap<>();
        List<String> list = new ArrayList<>();
        Iterator<String> item = map.keySet().iterator();
        while (item.hasNext()) {
            String keyNext = item.next();
            //将错误信息防在第一列，显示在excel第一列
            if (keyNext.equals("错误信息")) {
                list.add(0, keyNext);
            } else {
                list.add(keyNext);
            }
        }
        Iterator<String> item2 = list.iterator();
        while (item2.hasNext()) {
            String key = item2.next();
            sortedMap.put(key, map.get(key));
        }
        return sortedMap;
    }

    /**
     * 字典组查询
     *
     * @param
     * @return
     */
    public RespEntity dictList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String userId = token.getString("user_id");
        if (jsonParam.getStr("groupname").equals("系统类型")) {
            List<UseDict> list = useDictMapper.selectList(new QueryWrapper<UseDict>().eq("groupname", jsonParam.getStr("groupname")).orderByAsc("sortid"));
            List<String> userPerList = deviceBusinessMapper.getUserPer(userId);
            //根据权限返回系统列表
            list.removeIf(useDict -> !userPerList.contains(useDict.getPermissionId()));
            return RespEntity.success(list);
        }
        List<UseDict> list = useDictMapper.selectList(new QueryWrapper<UseDict>().eq("groupname", jsonParam.getStr("groupname")).orderByAsc("sortid"));
        return RespEntity.success(list);
    }

    /**
     * 报警类型分组名称
     *
     * @param
     * @return
     */
    public RespEntity getAlarmTypeGroupName(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        QueryWrapper<UseDict> qw = new QueryWrapper();
        qw.like("groupname", "报警类型");
        qw.groupBy("groupname");
        qw.select("groupname");
        List<UseDict> list = useDictMapper.selectList(qw);
        return RespEntity.success(list);
    }

    /**
     * 前端是否对这个用户做报警处理
     *
     * @param
     * @return
     */

    public RespEntity isAlarm(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("isAlarmFor------------------------" + jsonParam);
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String alarmId = jsonParam.getStr("alarmId");
        if (alarmId == null || StrUtil.isBlank(alarmId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("flag", false);
            return RespEntity.success(map);
        }
        Map<String, Object> deviceAlarmLogAllToday = deviceAlarmLogAllTodayMapper.selectByLogId(alarmId);
        String allId = deviceAlarmLogAllToday.get("allId") != null ? deviceAlarmLogAllToday.get("allId").toString() : "";
        String businessId = deviceAlarmLogAllToday.get("businessId") != null ? deviceAlarmLogAllToday.get("businessId").toString() : "";
        String[] allIds = allId.split(",");
        List<String> list = new ArrayList<>();
        for (String ss : allIds) {
            list.add(ss);
        }
        boolean flag = false;
        if (userType.equals("1")) {//为机构用户
            if (list.contains(homeId)) {
                flag = true;
            }
        } else if (userType.equals("2")) {//为单位用户
            if (businessId.equals(homeId)) {
                flag = true;
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("flag", flag);
        logger.info("isAlarmFor--------------------map----" + flag);
        return RespEntity.success(map);
    }


    /**
     * 烟感报警消音
     *
     * @param jsonParam
     * @return
     */
    public RespEntity alarmSilencer(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number", jsonParam.getStr("number")));
        if (deviceBusiness.isEmpty()) {
            return RespEntity.fail("设备号不存在!");
        }
        JSONObject jsonObject = new JSONObject();
        if (deviceBusiness.getDeviceType().equals("21")) {
            //10221681
            jsonObject.put("number", jsonParam.getStr("number").substring(0, 7));
            jsonObject.put("code", "a800050004ff0104");
            rest(jsonObject, "smokeTcpClient", "smokeTcpClient", "tcp", "POST");
        } else {
            JSONObject command = new JSONObject();
            command.put("commandType", "SILENCE");
            command.put("deviceCode", jsonParam.getStr("number"));
            jsonObject.put("command", "{\\\"commandType\\\":\\\"SILENCE\\\",\\\"deviceCode\\\":\\\"" + jsonParam.getStr("number") + "\\\"}");
            jsonObject.put("hex", false);
            jsonObject.put("msgType", "cloudReq");
            jsonObject.put("termId", deviceBusiness.getTermId());
            logger.info(jsonObject.toString());
            silencer(jsonObject, "xiangyuniot", "config", "silencer", "alarmInfo");
        }
        return RespEntity.success();
    }

    /**
     * 烟感报警消音
     *
     * @param jsonParam
     * @return
     */
    public RespEntity test(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //DeviceBusiness deviceBusiness = deviceBusinessMapper.selectOne(new QueryWrapper<DeviceBusiness>().eq("number",jsonParam.getStr("number")));
        deviceBusinessMapper.updateToOffForFire(new JSONObject());
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 查询是否有未处置的报警信息
     * @Date Created in 10:18 2023/2/21
     */

    public RespEntity alarmCount(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String alarmId = jsonParam.getStr("alarmId");
        int count = 0;
        if (userType.equals("1")) {
            count = deviceAlarmLogMapper.selectCount(new QueryWrapper<DeviceAlarmLog>().eq("is_handle", 0).like("all_id", homeId));
        } else {
            count = deviceAlarmLogMapper.selectCount(new QueryWrapper<DeviceAlarmLog>().eq("is_handle", 0).eq("business_id", homeId));
        }
        if (count > 0) {
            return RespEntity.success(true);
        } else {
            return RespEntity.success(false);
        }
    }

    /**
     * @Author YangYu
     * @Description 批量更新可视化设备状态（定时器）
     * @Date Created in 14:05 2023/3/13
     * @Param []
     */

    public void updateVisualizationDeviceState() {
        QueryWrapper<DeviceBusiness> qw = new QueryWrapper<>();
        qw.eq("currentstate", "2");
        qw.and(wrapper -> wrapper.eq("device_classify", "6").or().eq("device_classify", "11").or().eq("device_classify", "12").or().eq("device_classify", "13"));
        int count = deviceBusinessMapper.selectCount(qw);
        if (count > 0) {
            List<DeviceAlarmLog> deviceAlarmLogList = deviceAlarmLogMapper.getVisualizationDeviceLog();
            deviceBusinessMapper.batchUpdateVisualizationDeviceState(deviceAlarmLogList);
        }
    }

    /**
     * @Author YangYu
     * @Description 报警事件查询
     * @Date Created in 15:19 2024/4/15
     * @Param [jsonParam]
     */

    public RespEntity eventList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //rest请求token验证接口，并获取返回值：
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        String alarmId = jsonParam.getStr("alarmId");
        List<DeviceAlarmEvent> deviceAlarmEventList = deviceAlarmEventMapper.selectList(new QueryWrapper<DeviceAlarmEvent>().eq("device_alarm_log_id",jsonParam.getStr("deviceAlarmLogId")).orderByDesc("time"));
        return RespEntity.success(deviceAlarmEventList);
    }

    /**
     * @Author YangYu
     * @Description 报警日历数据
     * @Date Created in 14:32 2024/4/16
     * @Param [jsonParam]
     */

    public RespEntity alarmCalendarList(JSONObject jsonParam){
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        QueryWrapper<DeviceAlarmLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("alarm_type_name","is_handle","alarmtime").eq("number",jsonParam.getStr("number")).likeRight("alarmtime",jsonParam.getStr("date")).orderByDesc("alarmtime");
        List<DeviceAlarmLog> deviceAlarmLogList = deviceAlarmLogMapper.selectList(queryWrapper);
        List<String> dateList = new ArrayList<>();
        for (DeviceAlarmLog deviceAlarmLog : deviceAlarmLogList){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(deviceAlarmLog.getAlarmtime());
            if (!dateList.contains(date)){
                dateList.add(date);
            }
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            deviceAlarmLog.set("alarmTime",sdf.format(deviceAlarmLog.getAlarmtime()));
        }
        List<JSONObject> list = new ArrayList<>();
        for (String date : dateList){
            List<DeviceAlarmLog> logList = new ArrayList<>();
            for (DeviceAlarmLog deviceAlarmLog : deviceAlarmLogList){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String date2 = sdf.format(deviceAlarmLog.getAlarmtime());
                if (date.equals(date2)){
                    logList.add(deviceAlarmLog);
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dateTime",date);
            jsonObject.put("items",logList);
            jsonObject.put("count",logList.size());
            list.add(jsonObject);
        }
        jsonParam.put("count",deviceAlarmLogList.size());
        jsonParam.put("items",list);
        return RespEntity.success(jsonParam);
    }
}
